import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:xianyu_school/utils/url.dart';
import 'package:xianyu_school/xianyuApp/entity/comments/comments.dart';
import 'package:xianyu_school/xianyuApp/entity/goods/goods.dart';
import 'package:xianyu_school/xianyuApp/message/messageDetailPage.dart';
import 'package:xianyu_school/xianyuApp/mine/Widgets/BallPulseIndicator.dart';
import 'package:fluttertoast/fluttertoast.dart';

class goodsdetail extends StatefulWidget {
  goodsdetail({Key key,this.g}) : super(key: key);
  final goods g;
  State<StatefulWidget> createState() {
    return _goodsdetail();
  }
}

class _goodsdetail extends State<goodsdetail> with AutomaticKeepAliveClientMixin{

  String url = urls().url;
  String username;
  String comment;
  bool follow = false;
  bool collect = false;
  var _getfollowstate;
  var _getcomments;
  List<comments> cs = [];
  final _formKey = new GlobalKey<FormState>();

  Future<void> getusername() async {
    broseHis();
  }

  @override
  void initState() {
    super.initState();
    _getfollowstate = getfollow();
    _getcomments = getcomments();
    getusername();
  }

  void _showMessageDialog(String message) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          title: Text('提示'),
          content: Text(message),
          actions: <Widget>[
            FlatButton(
              child: Text("ok"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  void posthttp(comments c) async {
    try{
      Response re = await Dio().post(url+"/goods/addcomment",data: c.toJson());
      setState(() {
        cs.add(c);
      });
    }
    catch(e){
      return ;
    }
  }

  void postcomment(){
    comments c = new comments();
    final form = _formKey.currentState;
    form.save();
    if(comment == '') {
      _showMessageDialog("评论不能为空");
      return;
    }
    else{
      c.comment = comment;
      c.username = username;
      c.goodsid = widget.g.goodsid;
    }
    posthttp(c);
  }
  
  Future<void> getcomments() async {
    try{
      Response re = await Dio().get(url+"/goods/getcomments",queryParameters: {"goodsid":widget.g.goodsid});
      if(re.data.toString()!="No more data"){
        var responseJson = json.decode(re.data.toString());
        responseJson.forEach((data) {
          setState(() {
            cs.add(comments.fromJson(data));
          });
        });
      }
      return re;
    }
    catch(e){
      return;
    }
  }

  Widget Comments(int index){
    if(cs[index].parentid==null){
      return GestureDetector(
        child: Text.rich(
            TextSpan(
                children: [
                  TextSpan(
                      text: cs[index].username,
                      style: TextStyle(
                          fontSize: 20.0,
                          color: Colors.red
                      )
                  ),
                  TextSpan(
                      text: "说：",
                      style: TextStyle(
                          fontSize: 20.0
                      )
                  ),
                  TextSpan(
                      text: cs[index].comment,
                      style: TextStyle(
                          fontSize: 20.0
                      )
                  )
                ]
            )
        ),
        onTap: (){
          TextEditingController _controller = TextEditingController();
          showCupertinoDialog(
            context: context,
            builder: (context){
              return CupertinoAlertDialog(
                title: Text("回复"),
                content: Card(
                  elevation: 0.0,
                  child: TextFormField(
                    controller: _controller,
                  )
                ),
                actions: [
                  CupertinoDialogAction(
                    child: Text("取消"),
                    onPressed: (){
                      Navigator.of(context).pop();
                    },
                  ),
                  CupertinoDialogAction(
                    child: Text("回复"),
                    onPressed: (){
                      print(_controller.text);
                      comments c = new comments();
                      c.comment = _controller.text;
                      c.username = username;
                      c.goodsid = widget.g.goodsid;
                      c.parentid = cs[index].commentid;
                      posthttp(c);
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            }
          );
          setState(() {

          });
        },
      );
    }
    else{
      return Text.rich(
          TextSpan(
              children: [
                TextSpan(
                    text:"        ",
                ),
                TextSpan(
                    text: cs[index].username,
                    style: TextStyle(
                        fontSize: 20.0,
                        color: Colors.red
                    )
                ),
                TextSpan(
                    text: "回复：",
                    style: TextStyle(
                        fontSize: 20.0
                    )
                ),
                TextSpan(
                    text: cs[index].comment,
                    style: TextStyle(
                        fontSize: 20.0
                    )
                )
              ]
          )
      );
    }
  }

  void buygood() async{
    try{
      Response re = await Dio().post(url+"/goods/buygoods",queryParameters: {"goodsid":widget.g.goodsid,"username":username,"price":widget.g.price});
    }
    catch(e){
      return;
    }
  }

  Future<void> getfollow() async {
    try{
      SharedPreferences pre = await SharedPreferences.getInstance();
      username = pre.getString("username");
      Response re = await Dio().get(url+"/users/getfollowstate",queryParameters: {"fromusername":username,"tousername":widget.g.username});
      if(re.data.toString()=="false") {
        print(1);
        setState(() {
          follow = false;
        });
      }
      else {
        setState(() {
          follow = true;
        });
      }
      return re;
    }
    catch(e){
      return;
    }
  }

  void following() async {
    try{
      Response re = await Dio().post(url+"/users/follow",queryParameters: {"fromusername":username,"tousername":widget.g.username});
      setState(() {
        follow = true;
      });
    }
    catch(e){
      return ;
    }
  }

  void unfollowing() async {
    try{
      Response re = await Dio().post(url+"/users/unfollow",queryParameters: {"fromusername":username,"tousername":widget.g.username});
      setState(() {
        follow = false;
      });
    }
    catch(e){
      return ;
    }
  }

  void broseHis() async {
    try{
      SharedPreferences pre = await SharedPreferences.getInstance();
      username = pre.getString("username");
      Response re = await Dio().post(url+"/users/addhis",queryParameters: {"username":username,"goodsid":widget.g.goodsid});
    }
    catch(e){
      return;
    }
  }

  Future<void> getcollectstate() async {
    try{
      Response re = await Dio().get(url+"/users/getcollectstate",queryParameters: {"username":username,"goodsid":widget.g.goodsid});
      return re;
    }
    catch(e){
      return;
    }
  }

  void collecting() async {
    try{
      Response re = await Dio().post(url+"/users/collect",queryParameters: {"username":username,"goodsid":widget.g.goodsid});
    }
    catch(e){
      return ;
    }
  }

  void uncollecting() async {
    try{
      Response re = await Dio().post(url+"/users/uncollect",queryParameters: {"username":username,"goodsid":widget.g.goodsid});
    }
    catch(e){
      return ;
    }
  }

  String touimg = "https://pics7.baidu.com/feed/a8773912b31bb051fb37de05c78e64b24bede083.jpeg?token=f02d22e51399a01c6c239e6247cec44f";

  @override
  Widget build(BuildContext context) {
    List<String> imgs = widget.g.img.split(";");
    return Scaffold(
        appBar: CupertinoNavigationBar(
          backgroundColor: Colors.yellow,
          middle: Text('详情'),
        ),
        body: SafeArea(
          child: Scrollbar(
            child: ListView(
              children: [
                //头像
                Container(
                  decoration: BoxDecoration(
                    border:Border(bottom:BorderSide(width: 1,color: Color(0xBBBBBB)) ),
                  ),
                  margin: EdgeInsets.all(10),
                  child:Row(
                    children: [
                      GestureDetector(
                        child: Container(
                          margin: EdgeInsets.fromLTRB(0.0,0.0,10.0,10.0),
                          height:50,
                          width: 50,
                          decoration: BoxDecoration(
                              image: DecorationImage(
                                image: NetworkImage(touimg),
                                fit: BoxFit.cover,
                              ),
                              shape: BoxShape.circle
                          ),
                        ),
                        onTap: (){
                          Navigator.push(context, MaterialPageRoute(builder: (_) {
                            return messageDetailPage(to: widget.g.username,);
                          }));
                        },
                      ),
                      Text(widget.g.username+"\n"+widget.g.updatetime.toString()),
                      Expanded(child: Text(" ")),
                      FutureBuilder(
                        future: _getfollowstate,
                          builder: (context,snapshot){
                            if(snapshot.hasData){
                              if(follow) {
                                return OutlineButton(
                                  child: Text('已关注'),
                                  textColor: Colors.orange,
                                  color: Colors.white,
                                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                                  borderSide: BorderSide(color: Colors.orange, width: 1),
                                  onPressed: () {
                                    unfollowing();
                                  },
                                );
                              }
                              else{
                                return OutlineButton(
                                  child: Text('未关注'),
                                  textColor: Colors.orange,
                                  color: Colors.white,
                                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                                  borderSide: BorderSide(color: Colors.orange, width: 1),
                                  onPressed: () {
                                    following();
                                  },
                                );
                              }
                            }
                            else return BallPulseIndicator(
                                color: Colors.black
                            );
                          })
                    ],
                  ),
                ),
                Container(
                  margin:EdgeInsets.fromLTRB(10.0,0.0,10.0,10.0),
                  height: 370,
                  child: ListView(
                    children: [
                      //详情
                      Text(widget.g.description),
                      //图片
                      Image.memory(
                          base64.decode(imgs[0]),
                          fit:BoxFit.fill
                      ),
                      Image.memory(
                          base64.decode(imgs[2]),
                          fit: BoxFit.fill
                      ),
                      //评论
                      Form(
                        key: _formKey,
                        child: TextFormField(
                          autofocus: false,
                          onSaved: (value) => comment = value.trim(),
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            hintText: '看对眼就留言问问更多细节',
                          ),
                        ),),
                      Row(
                        children: [
                          Expanded(child: Text(" ")),
                          OutlineButton(
                              child: Text('发布'),
                              onPressed: (){
                                postcomment();
                              }),
                        ],
                      ),
                      FutureBuilder(
                        future: _getcomments,
                        builder: (context, snapshot){
                          if(snapshot.hasData){
                            if (snapshot.data.toString()=="No more data"){
                              return Text("  ");
                            }
                            else{
                              return ListView.builder(
                                shrinkWrap: true,
                                itemBuilder:(BuildContext context, int index){
                                  return Comments(index);
                                },
                                itemCount: cs.length,
                              );;
                            }
                          }
                          else{
                            return Center(
                              child: BallPulseIndicator(
                                  color: Colors.black
                              ),
                            );
                          }
                        },
                      ),
                    ],
                  ),
                ),
                Container(
                  child: Row(
                    children: [
                      FutureBuilder(
                          future: getcollectstate(),
                          builder: (context,snapshot){
                            if (snapshot.hasData){
                              if(snapshot.data.toString()=="false") collect = false;
                              else collect = true;
                              if(collect){
                                return IconButton(
                                  icon: Image.asset("lib/xianyuApp/imgs/collected.png"),
                                  iconSize: 20,
                                  onPressed: () {
                                    uncollecting();
                                    setState(() {
                                      collect = false;
                                    });
                                  },
                                );

                              }
                              else{
                                return IconButton(
                                  icon: Image.asset("lib/xianyuApp/imgs/shoucang.png"),
                                  iconSize: 20,
                                  onPressed: () {
                                    collecting();
                                    setState(() {
                                      collect = true;
                                    });
                                  },
                                );
                              }
                            }
                            else return BallPulseIndicator(
                                color: Colors.black
                            );
                          }),
                      Text(
                        "      ￥"+widget.g.price.toString(),
                        style: TextStyle(
                            color: Colors.red,
                            fontSize: 20
                        ),
                      ),
                      Expanded(child: Text(" ")),
                      OutlineButton(
                        child: Text("购买"),
                        onPressed: (){
                          buygood();
                          Navigator.pop(context);
                          Fluttertoast.showToast(
                              msg: "购买成功",
                              toastLength: Toast.LENGTH_SHORT,
                              gravity: ToastGravity.BOTTOM,
                              timeInSecForIosWeb: 1,
                              backgroundColor: Colors.black45,
                              textColor: Colors.white,
                              fontSize: 16.0
                          );
                        },
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
        )
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}